/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, DatePicker, Form, Input, InputNumber, notification, Select, Table} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import ViewTitle from "../../../components/ViewTitle";
import {FormField, FormLayout, ModalFooter} from "antd-extra";
import notify from "../../../components/NotificationExtra";
import styles from "../../index.less";
import AutoCompletePlus from "../../../common/AutoCompletePlus";
import MaterialElement from "../../finance/modal/MaterialElement";
import ElementItem from "../../../components/ElementItem";


const {RangePicker} = DatePicker;

const {Option} = Select;
moment.locale('zh-cn');
const table = 'ProcureOrder';
@Form.create()
@connect(({
            sales,
            global,
            material,
            store, procure
          }) => ({...sales, ...material, ...global, ...procure, ...store}))
export default class XModalSelectProcureMaterialLot extends FormBase {
  constructor(props) {
    super(props);
    const {record = {}} = this.props;
    this.state = {...record};
  }

  /**
   * 界面新建时带入产品数量，用来和含量一起计算原料数量
   * useMaterials：可用的采购物料（不同的物料）
   * materialRecords：采购物料批次（单一物料），useMaterials切换时，materialRecords切换
   * materialRecords中按时间来计算占用
   * state中存储当前界面的数据，只有state中的无素为空时，才从props中取
   * @returns {JSX.Element}
   */

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    this.props.dispatch({
      type: 'procure/findUsedProcureMaterials',
      payload: {}
    });
    /**
     * 查找可用物料信息
     */
    const {selectMaterialCode} = this.state;
    const {form} = this.props;
    const materialCount = form.getFieldValue('materialCount');
    selectMaterialCode && this.props.dispatch({
      type: 'sales/findUsedMaterialRecord',
      payload: {code: selectMaterialCode, materialCount}
    });
  }

  componentWillUnmount() {
    this.state = {};
  }

  renderFoot = () => {
    const {foot, value, modalRef, form, callback, record = {}} = this.props;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {usedMaterialRecord = [], isEdit = false} = this.props;
              const {usedProcureMaterialLots, selectMaterial, selectMaterialValue, count} = this.state;
              if (usedMaterialRecord.length === 0) {
                notify({type: "warn", message: "占用数量为0！"});
              }

              // let _usedCount = 0, usedShippingFee = 0, cost = 0, materialCount = 0;
              // _.map(usedProcureMaterialLots, item => {
              //   const {usedCount = 0, useCount = 0, shippingFee = 0, price = 0, count = 0} = item;
              //
              //   if (usedCount > (count - useCount)) {
              //     notify({type: "error", message: "注意！物料用量大于采购可用数量！"});
              //     //  return;
              //   }
              //   if (usedCount > 0) {
              //     _usedCount += usedCount;
              //     usedShippingFee += shippingFee * (usedCount / count);
              //     cost += price * usedCount;
              //     materialCount += usedCount;
              //   }
              // });
              // const {usedLotId = "ULD" + new Date().valueOf()} = record;
              _.merge(values, selectMaterial);
              // const _price = cost / materialCount;
              // values.usedProcureMaterialLots = usedProcureMaterialLots;
              // values.materialCount = materialCount;
              values.count = count;
              // values.usedLotId = usedLotId;
              // values.cost = cost;
              // values.price = _price.toFixed(2);
              // values.usedShippingFee = usedShippingFee.toFixed(2);
              values.selectMaterialValue = selectMaterialValue;
              values.usedMaterialRecord = usedMaterialRecord;

              callback(values);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  getMaterialInfo() {
    const {usedMaterialRecord = [], form} = this.props;
    const {usedProcureMaterialLots = [],count} = this.state;

    const {
      materialContent = this.state.materialContent
    } = form.getFieldsValue();

    const materialCount = count * materialContent / 100;

    let cost = 0, procureShippingFee = 0;
    _.map(usedMaterialRecord, item => {
      const {_useCount = 0, shippingFee = 0, count = 0, price = 0} = item;
      cost += _useCount * price;
      const v = shippingFee * (_useCount / count);
      procureShippingFee += v;
    });
    return <div>
      <FormLayout form={form} cols={4}>
        <FormField
          label={'原料含量%'}
          required={true}
          name={'materialContent'} initialValue={materialContent}
        >
          <InputNumber disabled={usedProcureMaterialLots.length > 0} style={{width: '100%'}}></InputNumber>
        </FormField>
        <FormField
          label={'原料用量'} required
          name={'materialCount'} initialValue={materialCount}
        >
          <InputNumber disabled style={{width: '100%'}}></InputNumber>
        </FormField>

        <FormField
          label={'成本'}
          name={'cost'} initialValue={cost}
        >
          <Input disabled style={{width: '100%'}}></Input>
        </FormField>
        <FormField
          label={'采购运费成本'}
          name={'procureShippingFee'} initialValue={procureShippingFee.toFixed(2)}
        >
          <Input disabled style={{width: '100%'}}></Input>
        </FormField>
      </FormLayout>;
    </div>;
  }

  getMaterialOpt = (list) => {
    _.map(list, item => {
      const {name = "", subcategory = "", spec = "", type = "", number = "", code} = item;
      item.value = name + " " + subcategory + " " + spec + " " + type + " " + number + " " + code;
    });
    return list.map(opt => (
      <Option key={opt.code}
              value={opt.value}
              label={'material'}>
        {/*{<Tooltip title={opt.code+opt.name+" "+opt.subcategory+" "+opt.spec}> {opt.name}</Tooltip>}*/}
        {opt.value}
      </Option>
    ));
  };

  onSearch = searchText => {
    const {materials = []} = this.props;

    if (!searchText || searchText === '') {
      this.state.materials = materials;
      const _temp = this.state;
      this.setState(_temp);
      return;
    }

    const temp = [];
    _.map(this.props.materials, item => {
      const {name} = item;
      if (name.includes(searchText)) {
        temp.push(item);
      }
    });
    const _temp = this.state;
    _temp.materials = temp;
    this.setState(_temp);
  };

  cols = [
    {
      title: "物料", dataIndex: 'code', key: 'code', render: (value, record) => {
        const {code, name} = record;
        return <MaterialElement code={code} name={name}></MaterialElement>;
      }
    },
    {
      title: "规格形态", dataIndex: 'code', key: 'code', render: (value, record) => {
        const {subcategory, spec} = record;
        return <MaterialElement subcategory={subcategory} spec={spec}></MaterialElement>;
      }
    },
    {
      title: "类型编号", dataIndex: 'code', key: 'code', render: (value, record) => {
        const {type, number} = record;
        return <MaterialElement type={type} number={number}></MaterialElement>;
      }
    },
    {
      title: "采购单编码", dataIndex: 'procureOrderCode', key: 'procureOrderCode', render: (value, record) => {
        const {vendor} = record;
        const data = [{key: '采购编码', value: value}, {key: '供应商', value: vendor}];
        return <ElementItem data={data}></ElementItem>;
      }
    },


    {
      title: "采购数量", dataIndex: 'count', key: 'count', render: (value, record) => {
        const {useCount = 0, inboundCount = 0} = record;
        const color = value - useCount > 0 ? '#22f' : '#f22';
        const data = [{key: '采购数量', value: value}, {
          key: '可用数量',
          value: <div style={{color}}>{value - useCount}</div>
        },
          {key: '入库数量', value: inboundCount}
        ];
        return <ElementItem data={data}></ElementItem>;
      }
    },
    {
      title: "占用数量", dataIndex: '_useCount', key: '_useCount'
      // render: (value, record) => {
      //   const {usedCount = 0} = record;
      //   return <a onClick={() => {
      //     ModalView.open(ModalEditUsedMaterialLotCount, {title: '修改占用数量', width: '920px'}, {
      //       usedCount: value,
      //       callback: data => {
      //         record.usedCount = data.usedCount;
      //         this.componentDidMount();
      //       }
      //     });
      //   }}>{usedCount}</a>;
      // }
    },
    {title: "去向", dataIndex: 'target', key: 'target'},
    {title: "单价", dataIndex: 'price', key: 'price'},
    {title: "采购单运费", dataIndex: 'shippingFee', key: 'shippingFee'},
    {
      title: "采购时间", dataIndex: 'createdTs', key: 'createdTs', render: value => {
        return <div>{moment(value).format('YYYY-MM-DD')}</div>;
      }
    },
    {
      title: "占用运费", dataIndex: 'shippingFee', key: 'shippingFee', render: (value, record) => {
        const {shippingFee = 0, _useCount = 0, count = 0} = record;
        console.log('shipping fee', shippingFee, _useCount, count);
        const v = shippingFee * (_useCount / count);
        return <div>{v.toFixed(2)}</div>;
      }
    }
    // {
    //   title: "修改占用数量", dataIndex: 'usedCount', key: 'usedCount', render: (value, record) => {
    //
    //     return <a onClick={() => {
    //       ModalView.open(ModalEditUsedMaterialLotCount, {title: '修改占用数量', width: '920px'}, {
    //         usedCount: value,
    //         callback: data => {
    //           console.log('edit used', data, record);
    //           record.usedCount = data.usedCount;
    //           this.componentDidMount();
    //         }
    //
    //       });
    //     }}>修改</a>;
    //   }
    // }
  ];

  makeUsedCount() {
    const {form} = this.props;
    this.state.usedProcureMaterialLots = this.props.usedProcureMaterialLots;
    const payload = form.getFieldsValue();
    const {materialCount} = payload;
    const {usedProcureMaterialLots} = this.state;
    const {count = 0, useCount = 0} = usedProcureMaterialLots[0];
    if (count - useCount > materialCount) {
      usedProcureMaterialLots[0].usedCount = materialCount;
    } else {
      usedProcureMaterialLots[0].usedCount = count - useCount;
    }
  }

  render() {
    const {style, useMaterials = [], usedMaterialRecord = [], form, isEdit = false} = this.props;
    let {loading, usedProcureMaterialLots = [], selectMaterialValue} = this.state;
    console.log('this.props.used', this.props.usedProcureMaterialLots);
    if (usedProcureMaterialLots.length === 0
      && this.props.usedProcureMaterialLots && this.props.usedProcureMaterialLots.length > 0) {
      this.makeUsedCount();
    }
    if (usedProcureMaterialLots && usedProcureMaterialLots.length > 0
      && this.props.usedProcureMaterialLots && this.props.usedProcureMaterialLots.length > 0
      && this.state.usedProcureMaterialLots[0].code !== this.props.usedProcureMaterialLots[0].code) {
      this.makeUsedCount();
    }
    if (!isEdit && this.props.usedProcureMaterialLots && this.props.usedProcureMaterialLots.length === 0) {
      this.state.usedProcureMaterialLots = [];
    }
    const payload = form.getFieldsValue();
    const {materialContent = this.state.materialContent} = payload;

    return (
      <Form style={{...style}}>
        {this.getMaterialInfo()}
        {materialContent === 0 && <div style={{marginLeft: '24px', color: '#f22'}}>请输入原料含量</div>}
        {
          materialContent > 0 && <AutoCompletePlus style={{width: '200%', margin: '12px'}}
                                                   addonBefore="选择物料:"
                                                   dataSource={this.getMaterialOpt(useMaterials)}
                                                   allowClear
                                                   onSearch={this.onSearch}
                                                   defaultValue={selectMaterialValue}
                                                   onChange={value => {
                                                     //  form.setFieldsValue({store: undefined});
                                                   }}
                                                   onSelect={(value, option) => {
                                                     const {key} = option;
                                                     this.state[`selectMaterialCode`] = key;
                                                     this.state[`selectMaterialValue`] = value;

                                                     this.state[`selectMaterial`] = _.find(useMaterials, item => {
                                                       return item.code === key;
                                                     });

                                                     this.state.materialRecords = [];

                                                     this.componentDidMount();
                                                   }}
          >
          </AutoCompletePlus>
          // </FormField> </FormLayout>
        }
        {materialContent > 0 && <ViewTitle
          title={'采购原料清单'}
          //  subTitle={str}
        ></ViewTitle>}

        {materialContent > 0 && <Table
          className={styles.antTable}
          bordered={true}
          rowKey={record => record.pmLotId}
          columns={this.cols}
          dataSource={usedMaterialRecord}
          scroll={{x: true}}
          //   rowSelection={rowSelection}
          loading={loading}
          // onRow={(record) => ({
          //   onClick: () => onSelectRow(record)
          // })}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
        ></Table>}

        {materialContent > 0 && this.renderFoot()}
      </Form>
    );
  }
}

